/**
 * Created by zaranengap on 2017/7/4.
 */
import React from "react";
import { connect } from "react-redux";
import { Layout, Menu, Breadcrumb, Icon, Tooltip, Divider, Popover, Input, message, Spin } from "antd";
import "styles/main/old-menu.scss";
import menuRoute from "routes/menuRoute";
import {
  setIsBydEnv,
  setIsConsoleEnv,
  setIsTcEnv,
  setIsWatsonsEnv,
  setReportMenu,
  setMenuCollapse,
  setMenuWidth,
} from "actions/main";
import { setAllCurrency } from "actions/cache";
import CommonFunctionsMenu from "containers/common-functions-menu/common-functions-menu";
import { deepFullCopy, messages, removeArrayItemByKey, ManuelResizeWindow } from "share/common";
import baseService from "share/base.service";
import CustomLogo from "containers/components/custom-logo";
import UserInfo from "containers/components/user-info";
import TryRegister from "containers/components/try-register";
import configureStore from "stores";
import routeService from "routes/route.service";
import RLService from "containers/data-center/report/report-list.service";
import CommonStatus from "containers/unbox-setting/common-status/common-status";
import SVGIcon from "components/SVGIcon";
import backGroundImg from "images/home/background.jpg";
import newTipImg from "images/home/new-tip.png";
import debounce from "lodash.debounce";
import { setProfile } from "actions/login";
import {
  RenderTrialOrTestInfo,
  RenderCompanyName,
  RenderMenuBottomFunc,
  RenderMessagesCenterSvg,
  RenderToolMenuListSvg,
  renderBreadcrumb,
  goIndex,
  matchMenuValue,
  resizeWidth,
  onKeyDown,
  inputChange,
  clearMenuSearch,
  checkHasMenuValue,
  renderSelectedKeys,
} from "./menu-share";

const { SubMenu } = Menu;
const { Header, Sider } = Layout;
const menuCollapseWidth = 64;
class OldMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      menu: props.menuTree.menuTree,
      collapsed: false,
      selectedKeys: [],
      openKeys: [],
      routeIsShow: {
        "sub-application-view": true,
        "mileage-subsidy-expense": true,
      },
      operatingVisible: false,
      toolMenuList: [],
      resultMenu: [],
      menuValue: "",
      isSearchingMenu: false,
      haveCommonFuncOption: false, //是否有常用功能菜单
      stateMenuTree: undefined, //  从props拿到的菜单 保存到state  好进行添加收藏菜单
      isEditCommonFunctions: false, //是否在编辑常用功能
      commonFunctionsList: [], //收藏菜单key值数组
      isCommonFunctionsEmpty: false, //收藏菜单是否为空
      delayFlag: false, //常用菜单的 延时flag 用于 保存后 300ms 再置为false 为true时 菜单始终更新
      commonFunctionsLoading: false, //常用菜单 保存按钮 loading
      showBindModal: false, //绑定手机号模态框 显隐控制
      hoverKey: "", //搜索菜单时键盘上下移动时选中的菜单key
      hoverKeyParent: "", //搜索菜单时键盘上下移动时选中的菜单key的parent
      showUnboxSettingTip: false, //右上角 快捷设置 橙色NEW tip 是否显示
      menuChanged: false,
      menuSearching: false, //菜单正在调接口搜索
    };
    this.menuTree = null;
    this.resultMenuTree = null;
    this.menuValue = null;
    this.commonFunctionsMenuIndex = null; //常用功能在 menuTree 的 index
    this.onceClickedMenuKey = null; //从 常用功能点击的菜单 的 key
    this.onCollapseWithCF = false; //打开的是 常用功能的 子菜单  时 点击 收起菜单的记录
    this.EditCommonFunctionsStatus = false; //折叠菜单的时候 判断 是否在 编辑常用功能 state 外的一个记录
    this.isReportMenuInited = false;
    this.setTipFalse = debounce(this.setTipFalse, 3000);
    this.resizeWindow = debounce(ManuelResizeWindow, 300);
    this.delayFlagOff = debounce(this.delayFlagOff, 300);
    this.searchMenu = debounce(this.searchMenu, 300);
    window.controlMenu = (key) => {
      this.onCollapse(key);
    };
  }

  setTipFalse = () => {
    this.setState({ showUnboxSettingTip: false });
  };

  setTipTrue = () => {
    this.setState({ showUnboxSettingTip: true });
  };

  componentWillMount() {
    this.renderToolMenu();
    window.scrollTo(0, 0);
    const hostname = window.location.hostname;
    if (hostname === "byd.huilianyi.com") {
      configureStore.store.dispatch(setIsBydEnv(true));
    }
    if (hostname === "console.huilianyi.com") {
      configureStore.store.dispatch(setIsConsoleEnv(true));
    }
    if (hostname === "console-tc.huilianyi.com") {
      configureStore.store.dispatch(setIsTcEnv(true));
    }
    if (hostname === "watsons.huilianyi.com") {
      configureStore.store.dispatch(setIsWatsonsEnv(true));
    }
  }

  componentDidMount() {
    this.checkCommonFunctions();
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  checkCommonFunctions = (nextTree) => {
    const menuTree = nextTree || this.props.menuTree.menuTree;
    let hasFlag = false;
    const commonFunctionsList = [];
    let haveCommonFuncOption = false;
    let menuIndex;
    menuTree.forEach((item, index) => {
      if (item.key === "common-functions") {
        if (
          !(
            item.subMenuTree[0].key === "common-functions-empty" ||
            item.subMenuTree[0].key === "common-functions-empty-star"
          )
        ) {
          item.subMenuTree.forEach((item) => {
            commonFunctionsList.push(item.key);
          });
          hasFlag = true;
        }
        menuIndex = index;
        haveCommonFuncOption = true;
      }
    });
    this.commonFunctionsMenuIndex = menuIndex;
    if (hasFlag) {
      this.setState({
        stateMenuTree: menuTree,
        commonFunctionsList,
        haveCommonFuncOption,
        isCommonFunctionsEmpty: false,
      });
    } else {
      this.setState({
        stateMenuTree: menuTree,
        haveCommonFuncOption,
        isCommonFunctionsEmpty: true,
      });
    }
  };
  componentWillReceiveProps(nextProps) {
    if (this.props.reportMenu !== nextProps.reportMenu) {
      this.menuTree = null;
    }
    if (this.state.collapsed !== nextProps.menuCollapse) {
      this.setState({ collapsed: nextProps.menuCollapse });
    }

    const before = this.props.menuTree.menuTree;
    const now = nextProps.menuTree.menuTree;
    if (now !== before) {
      const nowBool = now.filter((item) => item.functionCode === "common-functions");
      const roleMenu = nextProps.menuTree.keyUrl["role-menu-setting"];
      if (nowBool) {
        this.checkCommonFunctions(now);
      }
      this.setState({
        menuChanged: true,
        stateMenuTree: now,
      });
      if (!roleMenu) {
        this.context.router.push("/main/dashboard");
      }
    } else {
      this.setState({
        menuChanged: false,
      });
    }
    const { openKeys } = this.state;
    if (this.props.params.openKeys !== nextProps.params.openKeys && !openKeys.includes("common-functions")) {
      this.setState({
        openKeys: nextProps.params.openKeys,
      });
    }
  }

  renderToolMenu = () => {
    const { menuTree } = this.props;
    const tool = menuTree.menuTree.filter((item) => item.key === "toolbar");
    let toolMenu = [];
    let toolMenuList = [];
    if (tool && tool.length) {
      toolMenu = tool[0].subMenuTree.filter((item) => ["help-center-user"].indexOf(item.key) !== -1);
      if (toolMenu && toolMenu.length) {
        toolMenuList = toolMenu[0].subMenuTree;
        if (toolMenuList && toolMenuList.length) {
          this.setState({
            toolMenuList,
          });
        }
      }
    }
  };

  onCollapse = (collapsed, shouldFocusMenuInput) => {
    resizeWidth();
    const { selectedKeys, openKeys, isEditCommonFunctions } = this.state;
    const { menuTree } = this.props;
    configureStore.store.dispatch(setMenuCollapse(collapsed));
    this.setState({ collapsed, delayFlag: true }, () => {
      this.resizeWindow();
      this.delayFlagOff();
    });
    if (collapsed) {
      if (openKeys[0] === "common-functions") {
        this.onCollapseWithCF = true;
      } else {
        this.onCollapseWithCF = false;
      }
      this.setState({ openKeys: [], isSearchingMenu: false, menuValue: "" });
      if (isEditCommonFunctions) {
        this.EditCommonFunctionsStatus = true;
        this.setState({ isEditCommonFunctions: false });
      }
      configureStore.store.dispatch(setMenuWidth(64));
    } else {
      const openMenuItem = menuTree.allAPIMenuItem[selectedKeys[0]];
      const keys = [];
      if (this.onCollapseWithCF) {
        keys.push("common-functions");
        keys.push(selectedKeys[0]);
      } else if (openMenuItem && openMenuItem.parent) {
        openMenuItem.parent.forEach((item) => {
          keys.push(item.key);
        });
      }
      this.setState({ openKeys: keys });
      if (this.EditCommonFunctionsStatus) {
        this.EditCommonFunctionsStatus = false;
        this.setState({ isEditCommonFunctions: true });
      }
      setTimeout(() => {
        shouldFocusMenuInput && this.menuInputRef.focus();
      }, 300);
      configureStore.store.dispatch(setMenuWidth(this.props.language.code === "it_IT" ? 250 : 220));
    }
  };

  getCurrencyList = () => {
    baseService.getCurrencyList("", "").then((res) => {
      configureStore.store.dispatch(setAllCurrency(res.data.rows));
    });
  };

  handleReportMenuCheck() {
    this.isReportMenuInited = true;
    RLService.getReportMenuPolicy().then((res) => {
      const { data } = res;
      if (data) {
        configureStore.store.dispatch(setReportMenu(data));
      }
    });
  }

  handleMenuClick = (e, parentMenuKey) => {
    let { openKeys } = this.state;
    const currentKey = e.key;
    if (currentKey === "data-analysis" && !openKeys.includes("data-analysis")) {
      this.handleReportMenuCheck();
    }
    if (parentMenuKey) {
      if (openKeys[1] === currentKey) {
        openKeys = [parentMenuKey];
      } else {
        openKeys = [parentMenuKey, currentKey];
      }
    } else if (openKeys[0] === currentKey) {
      openKeys = [];
    } else {
      openKeys = [currentKey];
    }
    this.setState({ openKeys });
  };

  //路由跳转
  menuRouterDeal = (item) => {
    routeService.menuRouterDeal(item, this.context, this.props.authToken);
  };

  goMenuPage = (item, isFromCommonFunctions) => {
    const { loginProfile, profile } = this.props;
    // profile 替换为 当前登录人的登录profile
    if (profile !== loginProfile) {
      configureStore.store.dispatch(setProfile(this.props.loginProfile));
    }

    if (["credential-export", "posting-date"].includes(item.key)) {
      const token = this.props.authToken.access_token;
      const obj = {
        "credential-export": "http://api.huilianyi.com/jclegend/#/expense-reports",
        "posting-date": `http://api.huilianyi.com/jinkoPassedFee/index.html#/passedfee?token=${token}`,
      };
      window.open(obj[item.key], "_blank");
    } else {
      if (isFromCommonFunctions) {
        //从常用功能 里 点击的菜单  储存一下key 路由变化哪儿做判断
        this.onceClickedMenuKey = item.key;
      }
      this.repeatMenuKey = "";
      // 处理报表菜单跳转
      if (item.functionCode.indexOf("/") !== -1) {
        // 由于报表的类型可能会变，加菜单时存的key也就变了，所以报表类型更改时需要在这里加一下，使其能匹配到更改后的类型
        const idMap = {
          32: "graphic-report",
          7: "universal-report",
          41: "graphic-report",
        };
        this.repeatMenuKey = item.functionCode;

        let [key, id] = item.functionCode.split("/");
        key = idMap[id] || key;
        let url = menuRoute.getPageUrlByKey(key);
        url = url.replace(":id", id);
        url = url.replace(":reportName", item.resourceName);
        this.context.router.push(url);
        return;
      }
      this.context.router.push(item.url);
    }
  };

  editCommonFunctions = (e) => {
    const { isEditCommonFunctions, openKeys } = this.state;
    e.preventDefault();
    e.stopPropagation();
    if (openKeys.length === 0 || (openKeys && openKeys[0] === "home") || (openKeys && openKeys[0] === "dashboard")) {
      this.save(isEditCommonFunctions, true);
    } else {
      this.save(isEditCommonFunctions, false);
    }
  };

  delayFlagOff = () => {
    this.setState({ delayFlag: false });
  };

  save = (isSave, openMenu) => {
    const { isEditCommonFunctions, commonFunctionsList } = this.state;
    if (isSave) {
      //调接口保存
      this.setState({ commonFunctionsLoading: true });
      baseService
        .addOrUpdateCommonFunctions(
          commonFunctionsList.map((item) => {
            return { key: item };
          })
        )
        .then((res) => {
          message.success(messages("basic-1.key66") /*保存成功*/);
          if (openMenu) {
            this.setState(
              {
                isEditCommonFunctions: !isEditCommonFunctions,
                openKeys: ["common-functions"],
                commonFunctionsLoading: false,
              },
              this.judgeStatus
            );
          } else {
            this.setState(
              {
                isEditCommonFunctions: !isEditCommonFunctions,
                commonFunctionsLoading: false,
              },
              this.judgeStatus
            );
          }
          this.delayFlagOff();
        });
    } else {
      //直接启用编辑状态
      if (openMenu) {
        this.setState(
          {
            isEditCommonFunctions: !isEditCommonFunctions,
            openKeys: ["common-functions"],
            delayFlag: true,
          },
          this.judgeStatus
        );
      } else {
        this.setState(
          {
            isEditCommonFunctions: !isEditCommonFunctions,
            delayFlag: true,
          },
          this.judgeStatus
        );
      }
    }
  };

  judgeStatus = () => {
    const { stateMenuTree, commonFunctionsList, isEditCommonFunctions } = this.state;
    const copyTree = deepFullCopy(stateMenuTree);
    const index = this.commonFunctionsMenuIndex;

    //判断是否为空
    if (commonFunctionsList.length === 0) {
      //收藏为空
      if (isEditCommonFunctions) {
        copyTree[index].subMenuTree = [
          {
            resourceName: "",
            key: "common-functions-empty-star",
          },
          {
            resourceName: "",
            key: "common-functions-empty",
          },
        ];
      } else {
        copyTree[index].subMenuTree = [
          {
            resourceName: "",
            key: "common-functions-empty",
          },
        ];
      }
    }
    this.setState({ stateMenuTree: copyTree });
  };

  //菜单里添加/取消 收藏
  addMoveFuncItem = (e, item) => {
    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }
    const { stateMenuTree, commonFunctionsList } = this.state;
    const copyTree = deepFullCopy(stateMenuTree);
    const bool = commonFunctionsList.indexOf(item.key) !== -1;
    const index = this.commonFunctionsMenuIndex;
    //正常的逻辑处理
    if (commonFunctionsList.length < 10 || bool) {
      if (!bool) {
        //添加
        copyTree[index].subMenuTree.push(item);
        commonFunctionsList.push(item.key);
      } else {
        //删除
        copyTree[index].subMenuTree = removeArrayItemByKey(copyTree[index].subMenuTree, item, "key");
        commonFunctionsList.delete(item.key);
      }
    } else {
      message.error(messages("basic-1.key67") /*常用功能个数已达上限，不能再添加*/);
      return;
    }
    //判断是否为空
    if (commonFunctionsList.length === 0) {
      //收藏为空
      copyTree[index].subMenuTree = [
        {
          resourceName: "",
          key: "common-functions-empty-star",
        },
        {
          resourceName: "",
          key: "common-functions-empty",
        },
      ];
    } else {
      //收藏不为空
      if (copyTree[index].subMenuTree[0].key === "common-functions-empty-star") {
        copyTree[index].subMenuTree = removeArrayItemByKey(
          copyTree[index].subMenuTree,
          { key: "common-functions-empty" },
          "key"
        );
        copyTree[index].subMenuTree = removeArrayItemByKey(
          copyTree[index].subMenuTree,
          { key: "common-functions-empty-star" },
          "key"
        );
      }
    }

    this.setState({ stateMenuTree: copyTree, commonFunctionsList });
  };

  commonFunctionsDragged = (list) => {
    const { stateMenuTree } = this.state;
    const copyTree = deepFullCopy(stateMenuTree);
    const index = this.commonFunctionsMenuIndex;
    copyTree[index].subMenuTree = [];
    list.forEach((item) => {
      stateMenuTree[index].subMenuTree.forEach((menu) => {
        if (menu.key === item) copyTree[index].subMenuTree.push(menu);
      });
    });
    this.setState({
      stateMenuTree: copyTree,
      commonFunctionsList: list,
    });
  };

  getMenuIconAndLongNameInfo = () => {
    const editIcon = `<i style="font-size: 12px" class="anticon anticon-edit"></i>`;
    const saveIcon = `<i style="font-size: 12px" class="anticon anticon-save"></i>`;
    const starIcon = `<i style="font-size: 12px" class="anticon anticon-star-o"></i>`;
    const tipEdit = messages("basic-1.key68", {
      arg1: editIcon,
    }); /*点击&nbsp;{arg1}可添加功能*/
    const tipSave = messages("basic-1.key69", {
      arg1: saveIcon,
    }); /*点击&nbsp;{arg1}可保存编辑*/
    const tipStar = messages("basic-1.key70", {
      arg1: starIcon,
    }); /*点击功能右侧&nbsp;{arg1}可添加*/
    const LongNameList = [
      "process-monitoring-platform",
      "loan-and-refund",
      "sub-application-view",
      "callback-setting",
      "invoice-source-check",
      "reimb-submission-control",
      "loan-max",
      "currency-setting",
      "audit-opinion",
      "tax-code",
      "auto-audit",
      "email-notification",
      "notification-setting",
      "airline-platform",
      "pay-backlash-recheck",
    ];
    return { tipEdit, tipSave, tipStar, LongNameList };
  };
  // 渲染子菜单
  repeatMenu = (menu, parentMenuKey, deep) => {
    const { code } = this.props.language;
    const EnglishEnv = !!(code === "en");
    const {
      collapsed,
      isEditCommonFunctions,
      commonFunctionsLoading,
      commonFunctionsList,
      menuValue,
      hoverKey,
      selectedKeys,
    } = this.state;
    const { tipEdit, tipSave, tipStar, LongNameList } = this.getMenuIconAndLongNameInfo();
    const handleReportMenu = (item) => {
      const { reportMenu } = this.props;
      if (!reportMenu || reportMenu.length === 0) {
        return null;
      }
      return this.repeatMenu(reportMenu, item.key, deep + 1);
    };
    // 常用功能
    const handleCommonSubMenu = (item, name) => {
      return (
        <SubMenu
          key={item.key}
          className="common-functions-menu-guid"
          onTitleClick={(e) => this.handleMenuClick(e, parentMenuKey)}
          title={
            <span className={item.parentId === "0" ? `first-menu ${code}` : `${code}`}>
              {item.resourceImage && <Icon type={item.resourceImage} />}
              <span className="nav-text">{name}</span>
              {!collapsed && (
                <Tooltip
                  title={isEditCommonFunctions ? messages("common.save") /*保存*/ : messages("common.edit") /*编辑*/}
                >
                  <Icon
                    onClick={this.editCommonFunctions}
                    type={commonFunctionsLoading ? "loading" : isEditCommonFunctions ? "save" : "edit"}
                    className="common-edit-icon"
                  />
                </Tooltip>
              )}
            </span>
          }
        >
          {this.repeatMenu(item.subMenuTree, item.key, deep + 1)}
        </SubMenu>
      );
    };
    // 普通功能菜单
    const handleOrdinarySubMenu = (item, name) => {
      const menuNameComp = (
        <span className={item.parentId === "0" ? `first-menu ${code}` : `${code}`}>
          {item.resourceImage && <Icon type={item.resourceImage} />}
          <span className="nav-text">
            {menuValue && checkHasMenuValue(item, menuValue) ? matchMenuValue(item, menuValue) : name}
          </span>
        </span>
      );
      return (
        <SubMenu
          key={item.key}
          onTitleClick={(e) => this.handleMenuClick(e, parentMenuKey)}
          title={
            (!collapsed &&
              EnglishEnv &&
              ["reconcilation-management", "borrowing-repayment-setting", "financial-accounting-setting"].indexOf(
                item.key
              ) !== -1) ||
            (code === "it_IT" && name.length > 25) ? (
              <Tooltip title={name}>{menuNameComp}</Tooltip>
            ) : (
              menuNameComp
            )
          }
        >
          {item.key === "data-analysis" && handleReportMenu(item)}
          {this.repeatMenu(item.subMenuTree, item.key, deep + 1)}
        </SubMenu>
      );
    };
    return (
      menu &&
      menu.map((item, index) => {
        if (!item.key) item.key = item.functionCode;
        const name = item.resourceName || messages(`menu.${item.key}`);
        const isStar = commonFunctionsList.indexOf(item.key) !== -1;
        //item.resourceType === "C" 代表该菜单是工具栏菜单，首页，仪表盘，组件库，快捷设置中心，都不在左侧菜单栏展示
        const isSkipedMenu = item.resourceType === "C" || ["home", "dashboard", "unbox-setting"].includes(item.key);
        return item.subMenuTree && item.subMenuTree.length ? (
          isSkipedMenu ? null : ["common-functions"].includes(item.key) ? (
            handleCommonSubMenu(item, name)
          ) : (
            handleOrdinarySubMenu(item, name)
          )
        ) : isSkipedMenu ? null : parentMenuKey === "common-functions" ? (
          item.key === "common-functions-empty" || item.key === "common-functions-empty-star" ? (
            <Menu.Item disabled key={item.key}>
              {item.key === "common-functions-empty" ? (
                <div className="single-f-menu" style={{ fontSize: "12px", width: "120%" }}>
                  {isEditCommonFunctions ? (
                    <Tooltip
                      placement="right"
                      title={
                        <span
                          dangerouslySetInnerHTML={{
                            __html: tipSave.replace(/i>/, "i>&nbsp;"),
                          }}
                        />
                      }
                    >
                      <span dangerouslySetInnerHTML={{ __html: tipSave }} />
                    </Tooltip>
                  ) : (
                    <Tooltip
                      placement="right"
                      title={
                        <span
                          dangerouslySetInnerHTML={{
                            __html: tipEdit.replace(/i>/, "i>&nbsp;"),
                          }}
                        />
                      }
                    >
                      <span dangerouslySetInnerHTML={{ __html: tipEdit }} />
                    </Tooltip>
                  )}
                </div>
              ) : (
                <div className="single-f-menu" style={{ fontSize: "12px", width: "120%" }}>
                  <Tooltip
                    placement="right"
                    title={
                      <span
                        dangerouslySetInnerHTML={{
                          __html: tipStar.replace(/i>/, "i>&nbsp;"),
                        }}
                      />
                    }
                  >
                    <span dangerouslySetInnerHTML={{ __html: tipStar }} />
                  </Tooltip>
                </div>
              )}
            </Menu.Item>
          ) : (
            <Menu.Item className="drag-menu" key={item.key}>
              <div className="single-f-menu">
                <span className={item.parentId === "0" ? `first-menu ${code}` : `${code}`}>
                  {item.resourceImage && <Icon type={item.resourceImage} />}
                  {!collapsed && EnglishEnv && LongNameList.indexOf(item.key) !== -1 ? (
                    <Tooltip title={name}>
                      <span className="nav-text">{name}</span>
                    </Tooltip>
                  ) : (
                    <span className="nav-text">{isEditCommonFunctions ? "" : name}</span>
                  )}
                </span>
              </div>
            </Menu.Item>
          )
        ) : (
          <Menu.Item key={item.key}>
            <div className={hoverKey === item.key ? "hove-menu-item" : "single-f-menu"} id={item.key}>
              <span className={item.parentId === "0" ? `first-menu ${code}` : `${code}`}>
                {item.resourceImage && <Icon type={item.resourceImage} />}
                {!collapsed &&
                ((EnglishEnv && LongNameList.indexOf(item.key) !== -1) || (code === "it_IT" && name.length > 25)) ? (
                  <Tooltip title={name}>
                    <span className="nav-text">{name}</span>
                  </Tooltip>
                ) : (
                  <span className="nav-text">
                    {selectedKeys[0] !== item.key && menuValue ? matchMenuValue(item, menuValue) : name}
                  </span>
                )}
              </span>
              {!(["common-functions", "component-lib"].indexOf(item.key) !== -1) &&
                !collapsed &&
                isEditCommonFunctions &&
                !(item.key.indexOf("/") !== -1) && ( //数据分析里 添加的报表菜单 不支持收藏
                  <Tooltip
                    placement="right"
                    title={isStar ? messages("basic-1.key71") /*移出常用*/ : messages("basic-1.key72") /*设为常用*/}
                  >
                    <Icon
                      onClick={(e) => {
                        this.addMoveFuncItem(e, item);
                      }}
                      className={menuValue.length ? "searched-icon" : "star-icon"}
                      type={isStar ? "star" : "star-o"}
                    />
                  </Tooltip>
                )}
            </div>
          </Menu.Item>
        );
      })
    );
  };

  getSubMenu(menu) {
    const {
      resultMenu,
      menuValue,
      isSearchingMenu,
      haveCommonFuncOption,
      menuChanged,
      hoverKey,
      isEditCommonFunctions,
      delayFlag,
    } = this.state;
    if (isSearchingMenu && resultMenu && resultMenu.length) {
      if (menuValue !== this.menuValue || haveCommonFuncOption || hoverKey) {
        this.menuValue = menuValue;
        this.resultMenuTree = this.repeatMenu(resultMenu, undefined, -1);
      }
      return this.resultMenuTree;
    }
    if (!this.menuTree) {
      this.menuTree = this.repeatMenu(menu, undefined, -1);
    } else if (haveCommonFuncOption && (isEditCommonFunctions || delayFlag)) {
      this.menuTree = this.repeatMenu(menu, undefined, -1);
    } else if (menuChanged) {
      this.menuTree = this.repeatMenu(menu, undefined, -1);
    }
    return this.menuTree;
  }

  onOpenChange = (openKeys) => {
    const { menuCollapse } = this.props;
    if (menuCollapse) this.setState({ openKeys: openKeys.slice(-1) });
  };

  onClickMenu = ({ item, key, keyPath }) => {
    const { menuTree, reportMenu } = this.props;
    if (keyPath.includes("common-functions")) {
      this.setState({ openKeys: ["common-functions"] });
    }
    if (keyPath.includes("data-analysis")) {
      const report = (reportMenu || []).find((item) => item.key === key);
      if (report) {
        this.goMenuPage(report, keyPath.includes("common-functions"));
        return;
      }
    }
    this.goMenuPage(menuTree.allAPIMenuItem[key], keyPath.includes("common-functions"));
  };

  renderMenu() {
    const { selectedKeys, openKeys, stateMenuTree } = this.state;
    const { menuTree, menuCollapse, language, menuWidth } = this.props;
    const props = {
      theme: "dark",
      mode: "inline",
      style: { width: menuCollapse ? menuCollapseWidth : menuWidth },
      selectedKeys: renderSelectedKeys(selectedKeys, this.props.params.selectedKeys),
      inlineCollapsed: menuCollapse,
      onOpenChange: this.onOpenChange,
      onSelect: (e) => {
        this.setState({ selectedKeys: [e.key] });
      },
      onClick: this.onClickMenu,
    };
    if (!menuCollapse) {
      props.openKeys = openKeys;
    }
    return <Menu {...props}>{this.getSubMenu(stateMenuTree || menuTree.menuTree)}</Menu>;
  }

  //渲染面板屑导航
  // todo
  // move main/components/
  renderBreadcrumb() {
    const { error } = this.props.params;
    return renderBreadcrumb(error);
  }

  //Route的渲染写在render外面，避免You cannot change <Router routes>; it will be ignored警告
  mainRoute = menuRoute.getMainRoute();

  searchMenu = () => {
    this.setState({
      menuSearching: true,
      isSearchingMenu: true,
    });
    baseService
      .searchMenu(this.state.menuValue)
      .then((res) => {
        this.setState({
          resultMenu: res.data,
          menuSearching: false,
        });
      })
      .catch((err) => {
        this.setState({
          resultMenu: [],
          menuSearching: false,
        });
      });
  };

  feedbackRefHandler = () => {
    this.feedbackRef.feedbackHandler();
  };

  goToUnboxSetting = (key) => {
    if (this.showTipTimmer) {
      clearTimeout(this.showTipTimmer);
      this.showTipTimmer = null;
    }
    this.setState({ popoverVisible: false }, () => {
      setTimeout(() => {
        this.context.router.push({
          pathname: menuRoute.getRouteItem("unbox-setting").url,
          state: { menuKey: key },
        });
      }, 300);
    });
  };

  renderUnboxSetting = () => {
    const { settingStatus } = this.props;
    const BASIC = settingStatus.filter((item) => item.moduleType === "BASIC")[0];
    const RECOMMEND = settingStatus.filter((item) => item.moduleType === "RECOMMEND")[0];
    const finishAll = BASIC.activate === BASIC.all && RECOMMEND.activate === RECOMMEND.all;

    return (
      <div className="popover-unbox-setting">
        <div className="content">
          <div className="tips-title">
            {
              finishAll
                ? messages("basic-1.key73") /*恭喜您，已完成全部设置，您可以继续了解高级功能*/
                : messages("basic-1.key74") /*快捷设置中心让您更高效的管理账户*/
            }
          </div>
          <CommonStatus
            goToUnboxSetting={(key) => {
              this.goToUnboxSetting(key);
            }}
          />
        </div>
        <div className="background-img-box">
          <img onMouseDown={(e) => e.preventDefault()} src={backGroundImg} className="background-image" />
        </div>
      </div>
    );
  };

  handleUnboxSettingVisible = (popoverVisible) => {
    if (!popoverVisible) {
      this.setState({ popoverVisible, showUnboxSettingTip: false });
    } else {
      this.setState({ showUnboxSettingTip: false });
      if (this.showTipTimmer) {
        clearTimeout(this.showTipTimmer);
        this.showTipTimmer = null;
      }
      this.showTipTimmer = setTimeout(() => {
        this.setState({ popoverVisible }, () => {
          if (popoverVisible) baseService.getTenantSettingStatus();
        });
      }, 300);
    }
  };

  render() {
    const { code } = this.props.language;
    const EnglishEnv = !!(code === "en");
    const {
      resultMenu,
      isSearchingMenu,
      menuValue,
      commonFunctionsList,
      openKeys,
      isEditCommonFunctions,
      stateMenuTree,
      selectedKeys,
      showUnboxSettingTip,
      popoverVisible,
      menuSearching,
      toolMenuList,
    } = this.state;
    const { loginUser, menuWidth, user, menuTree, loginCompany, tenant, location, menuCollapse } = this.props;
    const style = { marginBottom: 8, cursor: "pointer" };
    const { onlineServiceUrl } = this.props.params;
    return (
      <div className={`helios-main helios-main-${menuWidth}`}>
        <Sider
          collapsedWidth={menuCollapseWidth}
          width={menuCollapse ? menuCollapseWidth : menuWidth}
          className="helios-sider"
          collapsible
          trigger={null}
          collapsed={menuCollapse}
        >
          <RenderTrialOrTestInfo />
          <RenderCompanyName />
          <div
            className="menu-container"
            id="menu-container-guide-id"
            style={{
              height:
                tenant.licenseType === "TRIAL" || tenant.licenseType === "TEST"
                  ? "calc(100% - 128px)"
                  : "calc(100% - 104px)",
              width: menuCollapse ? menuCollapseWidth : menuWidth,
              overflow:
                openKeys[0] === "common-functions" && commonFunctionsList.length && isEditCommonFunctions
                  ? "hidden"
                  : "",
            }}
          >
            <div className="menu-search">
              {menuCollapse ? (
                <div
                  className="menu-search-collapsed"
                  onClick={() => {
                    this.onCollapse(!menuCollapse, true);
                  }}
                >
                  <Icon type="search" style={{ color: "#BCC8D4" }} />
                </div>
              ) : (
                <Input
                  ref={(ref) => (this.menuInputRef = ref)}
                  value={menuValue}
                  onKeyDown={(e) => onKeyDown(e, this)}
                  onChange={(e) => inputChange(e, this)}
                  placeholder={messages("basic-1.key79") /*搜索菜单*/}
                  prefix={<Icon type="search" style={{ color: "#BCC8D4" }} />}
                  suffix={
                    menuValue ? (
                      <Icon
                        type="close-circle"
                        style={{
                          color: "rgba(188, 200, 212,0.5)",
                          fontSize: 12,
                          cursor: "pointer",
                        }}
                        onClick={() => clearMenuSearch(this)}
                      />
                    ) : (
                      <span />
                    )
                  }
                />
              )}
            </div>
            {isSearchingMenu ? (
              menuSearching ? (
                <div className="no-result-menu">
                  <Spin spinning={menuSearching} />
                  &nbsp;&nbsp;
                </div>
              ) : resultMenu.length ? (
                <div className="search-result-menu" id="search-result-menu">
                  {this.renderMenu(resultMenu)}
                </div>
              ) : (
                <div className="no-result-menu">{messages("basic-1.key80") /*无相关菜单项*/}&nbsp;&nbsp;</div>
              )
            ) : (
              <div className="all-menu-list">
                {isSearchingMenu ? null : commonFunctionsList.length && openKeys[0] === "common-functions" ? (
                  <div
                    style={{
                      position: "absolute",
                      top: `42px`,
                      zIndex: "1",
                      width: "100%",
                      background: "#171E38",
                      overflow: "hidden",
                    }}
                  >
                    <CommonFunctionsMenu
                      menuWidth={menuWidth}
                      isEditCommonFunctions={isEditCommonFunctions}
                      selectedKeys={selectedKeys}
                      EnglishEnv={EnglishEnv}
                      addMoveFuncItem={(item) => {
                        this.addMoveFuncItem(null, item);
                      }}
                      goToPage={(item) => {
                        this.goMenuPage(item, true);
                      }}
                      onDraged={(list) => {
                        this.commonFunctionsDragged(list);
                      }}
                      subMenu={stateMenuTree[this.commonFunctionsMenuIndex]}
                    />
                  </div>
                ) : null}
                {this.renderMenu()}
              </div>
            )}
          </div>
          {/*试用账号显示注册入口*/}
          {user.tenantType === "FREE_TRIAL" && <TryRegister />}
          <RenderMenuBottomFunc onlineServiceUrl={onlineServiceUrl} that={this} />
        </Sider>
        <div
          style={{
            marginLeft: menuCollapse ? menuCollapseWidth : menuWidth,
            width: `calc(100% - ${menuCollapse ? menuCollapseWidth : menuWidth}px)`,
          }}
          className="content-layout"
        >
          <Header className="helios-header" style={{ width: `calc(100%)` }}>
            {CustomLogo(this.props.tenant, goIndex)}
            <div className="user-area">
              <span className="icon-area">
                {menuTree.allAPIMenuItem.home && (
                  <Popover
                    placement="bottomRight"
                    prefixCls={["zh_cn", "zh_tw"].indexOf(code) !== -1 ? "unbox-popover" : "en-unbox-popover"}
                    visible={popoverVisible}
                    onVisibleChange={this.handleUnboxSettingVisible}
                    trigger={window.location.pathname === "/main/unbox-setting" ? "none" : "hover"}
                    content={this.renderUnboxSetting()}
                  >
                    <span
                      id="user-guide-icon-id"
                      className="right-gap"
                      onClick={() => {
                        this.goToUnboxSetting("Basic");
                      }}
                    >
                      <SVGIcon
                        style={{ fontSize: 16, marginRight: 4, position: "relative", top: "-2px" }}
                        type={"unbox-setting-center"}
                      />
                      <span className="tip-text">{messages("basic-1.key82") /*快捷设置*/}</span>
                      <img src={newTipImg} className={`new-tip-img ${showUnboxSettingTip ? "show" : ""}`} />
                    </span>
                  </Popover>
                )}
                <RenderMessagesCenterSvg />
                <RenderToolMenuListSvg toolMenuList={toolMenuList} onlineServiceUrl={onlineServiceUrl} />
              </span>
              <Divider type="vertical" />
              <UserInfo loginUser={loginUser} menuRouterDeal={this.menuRouterDeal} />
            </div>
            {this.renderBreadcrumb()}
          </Header>
        </div>
      </div>
    );
  }
}

OldMenu.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    menuWidth: state.main.menuWidth,
    user: state.login.user,
    menuTree: state.login.menuTree,
    loginUser: state.login.loginUser,
    profile: state.login.profile,
    tenant: state.login.tenant,
    authToken: state.main.authToken,
    currentMenuPermission: state.main.currentMenuPermission,
    loginCompany: state.login.loginCompany,
    settingStatus: state.login.settingStatus,
    menuCollapse: state.main.menuCollapse,
    reportMenu: state.main.reportMenu,
    loginProfile: state.login.loginProfile,
  };
}

export default connect(mapStateToProps)(OldMenu);
